// 知识应用

// 知识的应用

// 考虑数据冗余
// es5写法
console.log('2222')
// function UiGoods(g)  {
//    this.data = g;
//    this.choose = 0;
//   //  this.totalPrice = 0;
  

// }
//ES6写法

class UIGoods {
  constructor(g){
    this.data = g;
    this.choose = 2;
  }
  totalPrice(){
      return this.data.price * this.choose
      
    }
    isChoose(){
        return this.choose > 0 
      }
      inCrease(func){
        this.choose ++
        // func()
      }
      deCrease(){
       this.choose == 0?0:this.choose -- 
      //  UIData.decrease()
      }
}
// // 获取总价
// UiGoods.prototype.totalPrice = function(){
//   return this.data.price * this.choose
// }
// // 是否选中了此商品
// UiGoods.prototype.isChoose = function(){
//   return this.choose > 0
// }
// 整个页面的数据
class UIData {
  constructor(){
    var UiGoods =[];
    for(let i =0;i<goods.length;i++){
      UiGoods.push(new UIGoods(goods[i]))
    }
    this.UiGoods = UiGoods
    this.deliveryThreshold = 30
    this.deliverPrice = 5
  }
  getTotalPrice(){
    // var sum = 0;
    // for(let i =0;i<this.UiGoods.length;i++){
    //   sum = +this.UiGoods[i].totalPrice()
    // }
    // 使用es6 reduce

    
   this.totalPrice = this.UiGoods.reduce(function(prev,cur){
        return prev + cur.totalPrice()
   },0)
   return this.totalPrice
    // this.sum = sum
  }

  // 增加某件商品的数量
  increase(index){
    this.UiGoods[index].inCrease()
    this.getTotalPrice()
    this.getTotalChooseNumber()

  }

  // 减少某件商品的数量
  decrease(index){
    this.UiGoods[index].deCrease(this.get)
    this.getTotalPrice()
    this.getTotalChooseNumber()

  }
  //得到总共的选择数量
  getTotalChooseNumber(){
    this.sum = this.UiGoods.reduce(function(prev,cur){
      return prev + cur.choose
    },0)
    return this.sum
  
  }
  hasGoodsInCar(){
    return this.getTotalChooseNumber() > 0
  }
  //是否达到配送的门槛
  isCrossDeliveryThreshold(){
      return this.getTotalPrice() > this.deliveryThreshold
  }
  //
  isChoose(index){
    return this.UiGoods[index].isChoose()
  }
}
// var ui = new UIData()


class UI {
  constructor(){
    this.UIData = new UIData();
    this.doms = {
      goodsContainer:document.querySelector('.goods-list'),
      deliveryPrice:document.querySelector('.footer-car-tip'),
      totalPrice:document.querySelector('.footer-car-total'),
      footerPay:document.querySelector('.footer-pay'),
      footerPayInnerSpan: document.querySelector('.footer-pay span'),
      car:document.querySelector('.footer-car'),
      badge: document.querySelector('.footer-car-badge'),

    }
    let carRect = this.doms.car.getBoundingClientRect()
      console.log(carRect)
      //目标位置
      let jumpTarget = {
        x:carRect.left + carRect.width/2,
        y:carRect.top + carRect.height/5
      }
      console.log(jumpTarget)
      this.jumpTarget = jumpTarget
    this.createHTML()
    this.updateFooter()
    this.listenAll()
  }
  //监听各种事件
  listenAll(){
    this.doms.car.addEventListener('animationend',function(){
      this.classList.remove('animate')
    })
  }
  // 根据商品数据创建商品列表元素
  createHTML(){
      // let frag = document.createDocumentFragment()
      // 1.生成html 字符串（parse Html）
      //   * 执行效率低,开发效率高
      console.log(this.UIData.UiGoods)
      let html = ``
      for(let i =0;i<this.UIData.UiGoods.length;i++){
        let data = this.UIData.UiGoods[i]
        html+=` <div class="goods-item ${data.choose > 0 ? 'active':''}">
        <img src="./assets/g1.png" alt="" class="goods-pic" />
        <div class="goods-info">
          <h2 class="goods-title">${data.data.title}</h2>
          <p class="goods-desc">
          ${data.data.desc}
          </p>
          <p class="goods-sell">
            <span>月售 200</span>
            <span>好评率${data.data.favorRate}%</span>
          </p>
          <div class="goods-confirm">
            <p class="goods-price">
              <span class="goods-price-unit">￥</span>
              <span>${data.data.price}</span>
            </p>
            <div class="goods-btns">
              <i data-index="${i}" class="iconfont i-jianhao"></i>
              <span >${data.choose}</span>
              <i data-index="${i}" class="iconfont i-jiajianzujianjiahao"></i>
            </div>
          </div>
        </div>
      </div>`
      }
      
      console.dir(this.doms)
 
      this.doms.goodsContainer.innerHTML = html
     
      // 2. 一个一个创建元素
      //   * 执行效率高，开发效率低
  }
  increase(index){
    this.UIData.increase(index)
    this.updateGoodsItem(index)
    this.updateFooter()
    this.jump(index)
  }
  decrease(index){
    this.UIData.decrease(index)
    this.updateGoodsItem(index)
    this.updateFooter()
  }
  // 更新商品的某个元素显示状态
  updateGoodsItem(index){
      let goodsDom = this.doms.goodsContainer.children[index]
      console.log(goodsDom)
      if(this.UIData.isChoose(index)){
        goodsDom.classList.add('active')
      }else{
        goodsDom.classList.remove('active')
      }
      var span = goodsDom.querySelector('.goods-btns span')
      span.textContent = this.UIData.UiGoods[index].choose
  }
  // 更新页脚
  updateFooter(){
    console.log(this.doms)
      this.doms.deliveryPrice.textContent = `配送费￥${this.UIData.deliverPrice}`
      console.log(this.UIData.getTotalPrice())
      this.doms.totalPrice.textContent = this.UIData.getTotalPrice().toFixed(2)
      console.log(this.UIData.isCrossDeliveryThreshold())
      if(this.UIData.isCrossDeliveryThreshold()){
        this.doms.footerPay.classList.add('active')
        this.doms.footerPayInnerSpan.textContent = `还差￥${Math.round(this.UIData.deliveryThreshold-this.UIData.getTotalPrice())}元起送`
      
      }else{
        this.doms.footerpay.classList.remove('active')
      }
      if(this.UIData.hasGoodsInCar){
        this.doms.car.classList.add('active')
        this.carAnimate()
      }else{
        this.doms.car.classList.remove('active')
      }
      // 设置购物车中的数量
      this.doms.badge.textContent = this.UIData.getTotalChooseNumber();
    
    }
    //购物车动画
    carAnimate(){
      this.doms.car.classList.add('animate')
     
    }
    //抛物线跳跃元素
    jump(index){
      let btnadd = this.doms.goodsContainer.children[index].querySelector('.i-jiajianzujianjiahao')
      console.log(btnadd)
      let rect = btnadd.getBoundingClientRect()
      let start = {
        x: rect.left,
        y: rect.top,
      };
      //跳吧
      let divJump = document.createElement('div');
      divJump.className = 'add-to-car';
      let i = document.createElement('i');
      i.className='iconfont i-jiajianzujianjiahao';
      // divJump.style.transform = `translate(${start.x}px,${start.y}px)`
      divJump.style.transform = `translateX(${start.x}px)`
      i.style.transform = `translateY(${start.y}px)`
      divJump.appendChild(i)
      document.body.appendChild(divJump)
      // 一种强制reflow
      // 合理的情况下我们可以是
      // requestAnimationFrame()
      divJump.clientHeight 
      //设置结束位置
      // js主线程直接渲染最终位置导致目前无效果
      divJump.style.transition = '1s'
      i.style.transition = '1s cubic-bezier(0.5,-0.5,1,1)'
      divJump.style.transform = `translateX(${this.jumpTarget.x}px)`
      i.style.transform = `translateY(${this.jumpTarget.y}px)`
      let that = this;
      divJump.addEventListener('transitionend',function(){
        divJump.remove();
        that.carAnimate();
      },
      {
        once: true, // 事件仅触发一次
      }
      )
      // this.carAnimate()
    }
    
}
console.log(ui)

// 开发思维需要考虑 平衡
var ui = new UI()

// 事件
ui.doms.goodsContainer.addEventListener('click', function (e) {
  if (e.target.classList.contains('i-jiajianzujianjiahao')) {
    var index = +e.target.getAttribute('data-index');
    ui.increase(index);
  } else if (e.target.classList.contains('i-jianhao')) {
    var index = +e.target.getAttribute('data-index');
    ui.decrease(index);
  }
});

window.addEventListener('keypress', function (e) {
  if (e.code === 'Equal') {
    ui.increase(0);
  } else if (e.code === 'Minus') {
    ui.decrease(0);
  }
});
